package com.zk.iotgateway.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *
 * 序列化工具类
 * @author:mn.m
 * @create 2019-04-25 上午 11:48
 **/
public class SerializationUtils {

    /*
    * 序列化
    * */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);//流對接

            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();

            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /*
    *
    * 反序列
    * */
    public static Object unserialize(byte[] bytes) {
        Object result = null;
        ByteArrayInputStream bais = null;

        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            result = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

}
